import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { WebsiteConfig } from '../types/website';
import { websiteService } from '../services/websiteService';

interface WebsiteState {
  config: WebsiteConfig | null;
  loading: boolean;
  error: string | null;
  fetchConfig: () => Promise<void>;
}

// 使用简单的Zustand store存储配置，并使用持久化中间件
// 这样网站配置只需加载一次，除非手动清除缓存
export const useWebsiteStore = create<WebsiteState>()(
  persist(
    (set) => ({
      config: null,
      loading: false,
      error: null,
      fetchConfig: async () => {
        try {
          // 如果已经有配置，就不重复加载
          const state = useWebsiteStore.getState();
          if (state.config) return;
          
          set({ loading: true, error: null });
          const response = await websiteService.getWebsiteConfig();
          set({ config: response.data, loading: false });
        } catch (error) {
          console.error('Failed to fetch website config:', error);
          set({ 
            error: error instanceof Error ? error.message : '获取网站配置失败', 
            loading: false 
          });
        }
      },
    }),
    {
      name: 'website-storage',
      storage: createJSONStorage(() => localStorage),
    }
  )
); 